var randArr=[1,2,5,40,80,120,,140]
$(function(){
	findUser();
	findMaType();
});
function findUser(){
	$("#userSelect").html("");
	var url="../../UserAction/query.action";
	var data=null;
	$.post(url,data,function(mes){
		$("#userSelect").append("<option value=''>====请选择====</option>");
		$.each(mes,function(index,item){
			$("#userSelect").append("<option value="+item.userId+">"+item.userName+"</option>");
			load();
		});
	},"json");
}
function findMaType(){
	$("#maTypeSelect").html("");
	var url="../../matype/query.action";
	var data=null;
	$.post(url,data,function(mes){
		$("#maTypeSelect").append("<option value=''>====请选择====</option>");
		$.each(mes,function(index,item){
			$("#maTypeSelect").append("<option value="+item.typeId+">"+item.typeName+"</option>");
			load();
		});
	},"json");
}
function exit(){
	$("#MaterislsLeft").html("");
	$("#materislsInput").val("");
	$("#maName").val("");
	$("#maTypeSelect").val("");
	$("#maxMoney").val("￥");
	$("#maxCount").val("￥");
	$("#purchaseBody").html("");
	$("#purIdInput").val("");
	load();
	//关闭所有页面层
	layer.closeAll('page');
}
layui.use(['form', 'layedit', 'laydate','table'], function(){
	var table = layui.table
	,laydate = layui.laydate
	,form = layui.form
	,layer = layui.layer
	,layedit = layui.layedit;

	table.on('checkbox(materislsDemo)', function(obj){
		var arr=table.cache.materisls;
		if(obj.type=="one"){
			console.info("单选"+obj.data);

			if(obj.checked){
				$("#materislsInput").val($("#materislsInput").val()+obj.data.maId+"@");
			}else{
				var arr=$("#materislsInput").val().split("@");
				var it="";
				$("#materislsInput").val("");
				$.each(arr,function(index,item){
					if(item!=obj.data.maId && item !=null && item!='' ){
						$("#materislsInput").val($("#materislsInput").val()+item+"@");
					}
				});
			}
		}else if(obj.type=="all"){
			console.info(arr);
			if(obj.checked){
				console.info("全选选中");
				$.each(arr,function(index,item){
					var state=0;
					$.each($("#materislsInput").val().split("@"),function(i,info){
						if(info==item.maId){
							state=1;
						}
					});
					if(state==0){
						$("#materislsInput").val($("#materislsInput").val()+item.maId+"@");
					}
				});

			}else{
				console.info("全选取消");
				$.each(arr,function(index,item){
					var arrs="";
					$.each($("#materislsInput").val().split("@"),function(i,info){
						if(info!=item.maId && info!='' && info!=null){
							arrs+=info+"@";
						}
					});
					$("#materislsInput").val(arrs);

				});
			}
		}

		$.ajaxSetup({
			async: false
		});

		setTimeout(function(){
			Checkbox();
		},200);

		$.ajaxSetup({
			async: true
		});


	});

	//监听工具条
	table.on('tool(demo)', function(obj){
		var da = obj.data;

		if(obj.event === 'edit'){
			layer.open({
				type: 1	 //此处以iframe举例
				,title: '修改采购单'
					,area: ['1000px','490px']
			,offset: 'auto'
				,content:$('#addOrUpdate')
				,success: function(layero){
					//执行重载
					table.reload('materisls', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
					//执行重载
					table.reload('purchase', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});

					var url="../../mapurchase/findByprichaseDetailId.action";
					var data={"purId":da.purId};
					$.post(url,data,function(mes){
						$("#purIdInput").val(mes.maPurchase.purId);
						$("#maxCount").val(mes.maPurchase.purCount);
						$("#maxMoney").val(mes.maPurchase.purMoney);
						$.each(mes.list,function(index,item){
							$("#materislsInput").val($("#materislsInput").val()+item.maId+"@");
							$("#purchaseBody").append("<tr>"
									+"<td class='purchasemaid'>"+item.maId+"</td>"
									+"<td>"+item.maName+"</td>"
									+"<td><input type='text' value="+item.deNumber+" id='number"+item.maId+"' class='materNumber' onkeyup='findkeyup(\""+item.maId+"\",\""+item.maMoney+"\")'/></td>"
									+"<td>"+item.maMoney+"</td>"
									+"<td><input type='text' id='sum"+item.maId+"' class='materSum' readonly='readonly' value="+item.deSum+" ></td>"
									+"</tr>");
							var rad=Math.floor(Math.random()*3); 
							$("#MaterislsLeft").append("<a name='a' class='tagc"+randArr[rad]+"' id="+item.maId+" onclick='findCheckBox(\""+item.maId+"\",\""+item.maName+"\");'>"+item.maName+"</a>");

						});



						$.each($(".layui-table-col-special"),function(index,item){
							console.info($(item).next().children().html());
							if($(item).next().children().html()!=undefined && $(item).next().next().children().html()!=''){
								$.each($("#materislsInput").val().split("@"),function(indexs,items){
									if(items==($(item).next().children().html())){
										console.info($(item).children().children(":first"));
										var check=$(item).children().children(":first").get(0);
										$(check).attr({"checked":true});

										load();
									}
								});
							};
						});

					},"json");

				},end : function() {
					$("#addOrUpdate").hide();
					exit();
				}
			});
		}else if(obj.event === 'del'){
			layer.confirm('真的删除行么',{title:"确认操作"}, function(index){
				var index = layer.load(0, {shade: false}); 
				var url="../../mapurchase/delete.action";
				var data={"purId":da.purId}
				$.post(url,data,function(mes){
					layer.close(index);
					if(mes==1){
						obj.del();
						layer.close(index);
						layer.msg("删除成功");
					}else{
						layer.msg("删除失败");
					}
				},"json");

			});
		}else if(obj.event === 'detail'){
			layer.open({
				type: 1	 //此处以iframe举例
				,title: '查看采购详情'
				,area: ['1000px','490px']
				,offset: 'auto'
				,content:$('#detailDiv')
				,success: function(layero){
					
					//执行重载
					table.reload('mapurDetailId', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					,where: {
						purId:da.purId
					}
					});
				},end:function(){
					$("#detailDiv").hide();
				}
			});
		}else if(obj.event === "audit"){
			layer.confirm('请确认提交审核',{title:"确认操作"},function(index){
			var index = layer.load(0, {shade: false}); 
			var url="../../mapurchase/updateAudit.action";
			var data={"purId":da.purId};
			$.post(url,data,function(mes){
				layer.close(index);
				if(mes==1){
					layer.msg("提交审核成功");
					//执行重载
					table.reload('idTest', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				}else{
					layer.msg("提交审核失败");
				}
			},"json");
			});
		}else if(obj.event === "make"){
			layer.confirm('请确认开始采购',{title:"确认操作"}, function(index){
			var index = layer.load(0, {shade: false}); 
			var url="../../mapurchase/updateState.action";
			var data={"purId":da.purId,"number":3};
			$.post(url,data,function(mes){
				layer.close(index);
				if(mes==1){
					layer.msg("开始采购");
					//执行重载
					table.reload('idTest', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				}else{
					layer.msg("开始采购失败");
				}
			},"json");
			});
		}else if(obj.event === "accomplish"){
			layer.confirm('请确认采购完成',{title:"确认操作"}, function(index){
			var index = layer.load(0, {shade: false}); 
			var url="../../mapurchase/accomplish.action";
			var data={"purId":da.purId};
			$.post(url,data,function(mes){
				layer.close(index);
				if(mes==1){
					layer.msg("采购完成");
					//执行重载
					table.reload('idTest', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				}else{
					layer.msg("采购完成失败");
				}
			},"json");
			});
		}else if(obj.event === "addMaQuality"){
			layer.confirm('请确认提交质检',{title:"确认操作"}, function(index){
			var index = layer.load(0, {shade: false}); 
			var url="../../mapurchase/addMaQuality.action";
			var data={"purId":da.purId};
			$.post(url,data,function(mes){
				layer.close(index);
				if(mes==1){
					layer.msg("提交质检成功");
					//执行重载
					table.reload('idTest', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
				}else{
					layer.msg("提交质检失败");
				}
			},"json");
			});
		}

});
var $ = layui.$, active = {
		reload: function(){
			var user = $('#userSelect');
			var oneMoney = $('#oneMoney');
			var twoMoney = $('#twoMoney');
			//执行重载
			table.reload('idTest', {
				page: {
					curr: 1 //重新从第 1 页开始
				}
			,where: {
				userId: user.val(),
				oneMoney: oneMoney.val(),
				twoMoney: twoMoney.val(),
			}
			});
		},
		Materisls:function(){
			var typeId = $('#maTypeSelect');
			var maName = $('#maName');
			//执行重载
			table.reload('materisls', {
				page: {
					curr: 1 //重新从第 1 页开始
				}
			,where: {
				maName: maName.val(),
				typeId: typeId.val(),
			}
			});
		}
		,getSave:function(){
			var index = layer.load(0, {shade: false}); 
			var sum="";
			$.each($("#purchaseBody tr"),function(index,item){
				console.info("材料id:"+$(item).children(":first").html());
				console.info("采购数量:"+$(item).children(":first").next().next().children(":first").val());
				sum+=$(item).children(":first").html()+","+$(item).children(":first").next().next().children(":first").val()+"@";
			});
			var url="../../mapurchase/addPurchaseDetail.action";
			var data={"sum":sum,"maxCount":$("#maxCount").val(),
					"maxMoney":$("#maxMoney").val(),
					"purId":$("#purIdInput").val()};
			$.post(url,data,function(mes){
				layer.close(index);
				if(mes==1){
					layer.msg('保存成功', {
						icon: 1
					});
					//执行重载
					table.reload('idTest', {
						page: {
							curr: 1 //重新从第 1 页开始
						}
					});
					$("#addOrUpdate").hide();
					exit();

				}else if(mes==2){
					layer.msg('抱歉公司财务余额不足，无法进行采购', {
						icon: 2
					});
				}else{
					layer.msg('保存失败', {
						icon: 2
					});
				}
			},"json");
		}
};

$('.demoTable #selectButton').on('click', function(){
	var type = $(this).data('type');
	active[type] ? active[type].call(this) : '';
});

$('.demoTable #insertSelect').on('click', function(){
	var type = $(this).data('type');
	active[type] ? active[type].call(this) : '';
});
$('#baoButton').on('click', function(){
	var type = $(this).data('type');
	active[type] ? active[type].call(this) : '';
});


$('.demoTable #insert').on('click', function(){
	layer.open({
		type: 1	 //此处以iframe举例
		,title: '增加采购单'
			,area: ['1000px','490px']
	,offset: 'auto'
		,content:$('#addOrUpdate')
		,success: function(layero){
			//执行重载
			table.reload('materisls', {
				page: {
					curr: 1 //重新从第 1 页开始
				}
			});
			//执行重载
			table.reload('purchase', {
				page: {
					curr: 1 //重新从第 1 页开始
				}
			});


		},end : function() {
			$("#addOrUpdate").hide();
			exit();
		}
	});
});


});
function findkeyup(id,money){
	if(isNaN($("#number"+id).val()) || $("#number"+id).val()==""){
		$("#number"+id).val(0);
	}else if($("#number"+id).val().length>7){
		$("#number"+id).val($("#number"+id).val().substring(0,$("#number"+id).val().length-1));
	}else{
		$("#sum"+id).val(parseInt($("#number"+id).val())*parseInt(money));
	}
	var count=0;
	$.each($(".materNumber"),function(index,item){
		count+=parseInt($(item).val());
	});
	var money=0;
	$.each($(".materSum"),function(index,item){
		money+=parseInt($(item).val());
	});
	$("#maxCount").val(count);
	$("#maxMoney").val(money);
}
function findCheckBox(maId,maName){
	$("#"+maId).remove();

	setTimeout(function(){
		Checkbox();
	},200);

	var arr=$("#materislsInput").val().split("@");
	$("#materislsInput").val("");
	$.each(arr,function(index,item){
		if(item!=maId && item !=null && item!='' ){
			$("#materislsInput").val($("#materislsInput").val()+item+"@");
		}
	});
	$.each($(".layui-table-col-special"),function(index,item){
		var name=$(item).next().next().next().children().html();
		if(name!=undefined && name!=''){
			if(name==maName){
				console.info($(item).children().children(":first"));
				var check=$(item).children().children(":first").get(0);
				$(check).attr({"checked":false});
				load();
			}
		};
	});

}
function Checkbox(){
	setTimeout(function(){
		var materSum="";
		$.each($(".materNumber"),function(nuI,nuItem){
			materSum+=$(nuItem).val()+","+nuItem.id+"@"
		});
		var count=0;
		var money=0;
		$("#purchaseBody").html("");
		$.each($("#materislsInput").val().split("@"),function(index,item){
			$("#MaterislsLeft").html("");
			var urls="../../materials/findById.action";
			var datas={"maId":item};
			$.post(urls,datas,function(info){
				console.info(info.maName);
				var rad=Math.floor(Math.random()*3); 
				//alert(randArr[rad]);
				//positionAll();
				//doPosition();
				$("#MaterislsLeft").append("<a name='a' class='tagc"+randArr[rad]+"' id="+info.maId+" onclick='findCheckBox(\""+info.maId+"\",\""+info.maName+"\");'>"+info.maName+"</a>");


				$("#purchaseBody").append("<tr>"
						+"<td class='purchasemaid'>"+info.maId+"</td>"
						+"<td>"+info.maName+"</td>"
						+"<td><input type='text' value='0' id='number"+info.maId+"' class='materNumber' onkeyup='findkeyup(\""+info.maId+"\",\""+info.maMoney+"\")' onkeydown='findkeyup(\""+info.maId+"\",\""+info.maMoney+"\")'/></td>"
						+"<td>"+info.maMoney+"</td>"
						+"<td><input type='text' id='sum"+info.maId+"' class='materSum' readonly='readonly' value='0'/></td>"
						+"</tr>"); 

				$.each(materSum.split("@"),function(is,infos){
					var shuzu=infos.split(",");
					$("#"+shuzu[1]).val(shuzu[0]);
				});
				$("#sum"+info.maId).val($("#number"+info.maId).val()*info.maMoney);
				if(parseInt($("#number"+info.maId).val())!=0){
					count+=parseInt($("#number"+info.maId).val());
				}
				if(parseInt($("#sum"+info.maId).val())!=0){
					money+=parseInt($("#sum"+info.maId).val());
				}
			},"json");
		});

		setTimeout(function(){
			if(count==null || count=='' || count==0){
				$("#maxCount").val(0);
			}else{
				$("#maxCount").val(count);
			}
			if(money==null || money=='' || money==0){
				$("#maxMoney").val(0);
			}else{
				$("#maxMoney").val(money);
			}


		},500);

	},100);
}
function load() {
	var form = layui.form
	form.render();
}